package com.teragadgets.android.comics.appengine;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Text;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Comic {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	@Persistent
	private String name;

	@Persistent
	private String url;

	@Persistent
	private Text altText;

	@Persistent
	private int number;

	@Persistent
	private Long webComic;

	public Comic(String name, String url, String altText, int number,
			Long webComic) {
		this.name = name;
		this.url = url;
		this.altText = new Text(altText);
		this.number = number;
		this.webComic = webComic;
	}

	public String getName() {
		return escapeXML(name);
	}

	public String getURL() {
		return url;
	}

	public String getAltText() {
		return escapeXML(altText.getValue());
	}

	public int getNumber() {
		return number;
	}

	public static String escapeXML(String s) {
		StringBuilder result = new StringBuilder();
		StringCharacterIterator i = new StringCharacterIterator(s);
		char c = i.current();
		while (c != CharacterIterator.DONE) {
			switch (c) {
			case '"':
				result.append("&quot;");
				break;
			case '\'':
				result.append("&#39;");
				break;
			case '&':
				result.append("&amp;");
				break;
			default:
				result.append(c);
			}
			c = i.next();
		}
		return result.toString();
	}
}
